package com.shanjupay.apiagent.interceptor;

import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;


@Component
public class VerificationInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String reqData = null;

        if(HttpMethod.GET.matches(request.getMethod())){
            reqData = request.getParameter("reqData");
        }else if(HttpMethod.POST.matches(request.getMethod())){
            reqData = getBodyString(request.getReader());
        }else {

        }

        //TODO：校验平台，参数签名等信息
        String signature = request.getParameter("signature");
        //验证签名，使用cn.itcast.wanxinp2p.common.util.RSAUtil实现
        if(!verifySignature(signature, reqData)){
            responseOut(response,"验证签名未通过:" + reqData);
            return false;
        }

        return true;
    }

    private boolean verifySignature(String signature, String reqData) {
        //TODO：验证签名，使用com.shanjupay.common.util.RSAUtil实现
        return  true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


    public static String getBodyString(BufferedReader br) throws IOException {
        String inputLine;
        StringBuilder str = new StringBuilder();
        while ((inputLine = br.readLine()) != null) {
            str.append(inputLine);
        }
        br.close();
        return str.toString();
    }

    public static void responseOut(HttpServletResponse response,String s){
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        try (
                PrintWriter pw = response.getWriter()
        ){
            pw.write(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
